package weixin02.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import weixin02.entity.User;
import weixin02.dao.UserDao;
import weixin02.service.UserService;
import org.springframework.stereotype.Service;
import weixin02.util.CommonUtil;
import weixin02.util.HttpClientUtil;
import weixin02.util.R;
import weixin02.util.ResultCode;

import javax.annotation.Resource;
import java.util.List;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2021-07-06 21:14:24
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;


    //微信登录
    @Override
    public R userLogin(String code,String nickName,int gender,String avatarUrl,String country,String province,String city) {
        String httpUrl = "https://api.weixin.qq.com/sns/jscode2session?appid="+CommonUtil.APPID +"&secret="+CommonUtil.SECRET+ "&js_code="+code+"&grant_type=authorization_code";
        try {
            //1.请求
            String result = HttpClientUtil.doGet(httpUrl);
            System.out.println(result);
            //2.把字符串转json
            JSONObject jsonResult = JSONObject.parseObject(result);
            //3.获取openid
            String openid =(String) jsonResult.get("openid");
            //4. 判断user表是否已经有用户
            //4.1 根据openid查询user表
            User user = userDao.queryUserByOpenid(openid);
            if(user==null){
                System.out.println("save");
                User u = new User();
                u.setOpenid(openid);
                u.setNickname(nickName);
                u.setGender(gender);
                u.setAvatarurl(avatarUrl);
                u.setCountry(country);
                u.setProvince(province);
                u.setCity(city);

                userDao.insert(u);
            }else {
                System.out.println("更新登录时间");
            }
            return  new R(jsonResult, ResultCode.SUCCESS);
        } catch (Exception e) {
            System.out.println(e);
            return  new R(ResultCode.FAIL);
        }

    }

    /*插入微信用户信息*/
    @Override
    public R insertUser(User user) {
        return null;
    }
    /*更新微信用户信息*/
    @Override
    public R updateUser(User user) {
        return null;
    }


}
